<template>
  <div class="statistics-page">
    <h2 class="page-title">统计分析</h2>
    
    <!-- 综合统计卡片 -->
    <el-row :gutter="20" class="overview-stats">
      <el-col :xs="12" :sm="6" :md="6" :lg="6">
        <el-card class="stat-card primary-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ studentStore.totalStudents }}</div>
              <div class="stat-label">总学生数</div>
              <div class="stat-change">+5.2%</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="6" :md="6" :lg="6">
        <el-card class="stat-card success-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ overallAverage }}</div>
              <div class="stat-label">平均成绩</div>
              <div class="stat-change">+2.1%</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="6" :md="6" :lg="6">
        <el-card class="stat-card warning-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><StarFilled /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ overallPassRate }}%</div>
              <div class="stat-label">及格率</div>
              <div class="stat-change">+1.8%</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="6" :md="6" :lg="6">
        <el-card class="stat-card danger-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Trophy /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ excellentRate }}%</div>
              <div class="stat-label">优秀率</div>
              <div class="stat-change">+3.2%</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-section">
      <!-- 成绩分布图 -->
      <el-col :xs="24" :sm="12" :md="12" :lg="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>成绩分布统计</span>
            </div>
          </template>
          <div class="score-distribution">
            <div class="score-range" v-for="range in scoreRanges" :key="range.label">
              <div class="range-label">{{ range.label }}</div>
              <div class="range-bar">
                <div 
                  class="range-fill" 
                  :style="{ width: `${range.percentage}%`, backgroundColor: range.color }"
                ></div>
              </div>
              <div class="range-value">{{ range.count }}人 ({{ range.percentage }}%)</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 性别分布图 -->
      <el-col :xs="24" :sm="12" :md="12" :lg="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>性别分布统计</span>
            </div>
          </template>
          <div class="gender-distribution">
            <div class="gender-chart-container">
              <div class="pie-chart">
                <div class="pie-slice male-slice" :style="maleSliceStyle"></div>
                <div class="pie-slice female-slice" :style="femaleSliceStyle"></div>
                <div class="pie-center">
                  <div class="total-count">{{ studentStore.totalStudents }}</div>
                  <div class="total-label">总人数</div>
                </div>
              </div>
              <div class="legend">
                <div class="legend-item">
                  <div class="legend-color male-color"></div>
                  <span>男生: {{ studentStore.maleStudents }}人</span>
                </div>
                <div class="legend-item">
                  <div class="legend-color female-color"></div>
                  <span>女生: {{ studentStore.femaleStudents }}人</span>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 班级成绩对比 -->
    <el-row :gutter="20" class="class-comparison">
      <el-col :span="24">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>班级成绩对比</span>
              <el-select v-model="selectedSubject" placeholder="选择科目" size="small">
                <el-option
                  v-for="course in appStore.courses"
                  :key="course.id"
                  :label="course.name"
                  :value="course.name"
                />
              </el-select>
            </div>
          </template>
          <div class="class-scores">
            <div 
              class="class-score-item" 
              v-for="cls in classScores" 
              :key="cls.name"
            >
              <div class="class-name">{{ cls.name }}</div>
              <div class="score-bar">
                <div 
                  class="score-fill" 
                  :style="{ width: `${cls.score}%` }"
                ></div>
              </div>
              <div class="score-value">{{ cls.score }}分</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 月度趋势 -->
    <el-row :gutter="20" class="trend-section">
      <el-col :span="24">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>月度成绩趋势</span>
            </div>
          </template>
          <div class="trend-chart">
            <div class="trend-line">
              <div 
                class="trend-point" 
                v-for="(point, index) in trendData" 
                :key="index"
                :style="{ 
                  left: `${(index / (trendData.length - 1)) * 100}%`,
                  bottom: `${point.value}%`
                }"
                :title="`${point.month}: ${point.score}分`"
              >
                <div class="point-dot"></div>
                <div class="point-label">{{ point.score }}</div>
              </div>
            </div>
            <div class="trend-labels">
              <div 
                class="label-item" 
                v-for="(point, index) in trendData" 
                :key="index"
              >
                {{ point.month }}
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useStudentStore } from '../stores/student'
import { useAppStore } from '../stores/app'

const studentStore = useStudentStore()
const appStore = useAppStore()
const selectedSubject = ref('高等数学')

// 模拟数据
const mockScores = [75, 82, 68, 91, 87, 73, 95, 84, 79, 86, 92, 77, 89, 83, 76]

// 计算属性
const overallAverage = computed(() => {
  if (mockScores.length === 0) return 0
  const total = mockScores.reduce((sum, score) => sum + score, 0)
  return Math.round(total / mockScores.length)
})

const overallPassRate = computed(() => {
  if (mockScores.length === 0) return 0
  const passCount = mockScores.filter(score => score >= 60).length
  return Math.round((passCount / mockScores.length) * 100)
})

const excellentRate = computed(() => {
  if (mockScores.length === 0) return 0
  const excellentCount = mockScores.filter(score => score >= 90).length
  return Math.round((excellentCount / mockScores.length) * 100)
})

const scoreRanges = computed(() => {
  const ranges = [
    { label: '90-100分', min: 90, max: 100, color: '#67C23A' },
    { label: '80-89分', min: 80, max: 89, color: '#409EFF' },
    { label: '70-79分', min: 70, max: 79, color: '#E6A23C' },
    { label: '60-69分', min: 60, max: 69, color: '#F56C6C' },
    { label: '60分以下', min: 0, max: 59, color: '#909399' }
  ]

  return ranges.map(range => {
    const count = mockScores.filter(score => score >= range.min && score <= range.max).length
    const percentage = mockScores.length > 0 ? Math.round((count / mockScores.length) * 100) : 0
    return { ...range, count, percentage }
  })
})

const maleSliceStyle = computed(() => {
  const total = studentStore.totalStudents
  if (total === 0) return { transform: 'rotate(0deg)' }
  const angle = (studentStore.maleStudents / total) * 360
  return {
    transform: `rotate(${angle}deg)`
  }
})

const femaleSliceStyle = computed(() => {
  const total = studentStore.totalStudents
  if (total === 0) return { transform: 'rotate(0deg)' }
  const maleAngle = (studentStore.maleStudents / total) * 360
  const femaleAngle = (studentStore.femaleStudents / total) * 360
  return {
    transform: `rotate(${maleAngle}deg) rotate(${femaleAngle}deg)`
  }
})

const classScores = computed(() => {
  // 模拟成绩数据 - 根据选择的科目获取各班级的平均分
  const mockGrades = [
    // 高等数学
    { course_name: '高等数学', class_name: '网络工程班', scores: [85, 88, 82, 90, 87] },
    { course_name: '高等数学', class_name: '计算机科学与技术1班', scores: [77, 80, 75, 82, 78] },
    { course_name: '高等数学', class_name: '计算机科学与技术2班', scores: [76, 78, 74, 79, 77] },
    { course_name: '高等数学', class_name: '软件工程1班', scores: [85, 87, 83, 89, 86] },
    { course_name: '高等数学', class_name: '软件工程2班', scores: [84, 86, 82, 88, 85] },
    
    // 程序设计基础
    { course_name: '程序设计基础', class_name: '网络工程班', scores: [88, 90, 85, 92, 89] },
    { course_name: '程序设计基础', class_name: '计算机科学与技术1班', scores: [82, 85, 80, 87, 84] },
    { course_name: '程序设计基础', class_name: '计算机科学与技术2班', scores: [80, 83, 78, 85, 82] },
    { course_name: '程序设计基础', class_name: '软件工程1班', scores: [90, 92, 88, 94, 91] },
    { course_name: '程序设计基础', class_name: '软件工程2班', scores: [89, 91, 87, 93, 90] },
    
    // 数据结构
    { course_name: '数据结构', class_name: '网络工程班', scores: [78, 82, 76, 84, 80] },
    { course_name: '数据结构', class_name: '计算机科学与技术1班', scores: [75, 78, 73, 80, 77] },
    { course_name: '数据结构', class_name: '计算机科学与技术2班', scores: [74, 77, 72, 79, 76] },
    { course_name: '数据结构', class_name: '软件工程1班', scores: [82, 85, 80, 87, 84] },
    { course_name: '数据结构', class_name: '软件工程2班', scores: [81, 84, 79, 86, 83] },
    
    // 数据库原理
    { course_name: '数据库原理', class_name: '网络工程班', scores: [83, 86, 80, 88, 85] },
    { course_name: '数据库原理', class_name: '计算机科学与技术1班', scores: [79, 82, 77, 84, 81] },
    { course_name: '数据库原理', class_name: '计算机科学与技术2班', scores: [78, 81, 76, 83, 80] },
    { course_name: '数据库原理', class_name: '软件工程1班', scores: [86, 89, 84, 91, 88] },
    { course_name: '数据库原理', class_name: '软件工程2班', scores: [85, 88, 83, 90, 87] },
    
    // 计算机网络
    { course_name: '计算机网络', class_name: '网络工程班', scores: [90, 93, 88, 95, 92] },
    { course_name: '计算机网络', class_name: '计算机科学与技术1班', scores: [76, 79, 74, 81, 78] },
    { course_name: '计算机网络', class_name: '计算机科学与技术2班', scores: [75, 78, 73, 80, 77] },
    { course_name: '计算机网络', class_name: '软件工程1班', scores: [80, 83, 78, 85, 82] },
    { course_name: '计算机网络', class_name: '软件工程2班', scores: [79, 82, 77, 84, 81] }
  ]
  
  return appStore.classes.map(cls => {
    // 找到对应班级和科目的成绩数据
    const classGrades = mockGrades.find(grade => 
      grade.class_name === cls.name && grade.course_name === selectedSubject.value
    )
    
    let averageScore = 0
    if (classGrades && classGrades.scores.length > 0) {
      const total = classGrades.scores.reduce((sum, score) => sum + score, 0)
      averageScore = Math.round(total / classGrades.scores.length)
    } else {
      // 如果没有对应数据，使用默认分数
      averageScore = Math.floor(Math.random() * 15) + 75
    }
    
    return {
      name: cls.name,
      score: averageScore
    }
  })
})

const trendData = ref([
  { month: '9月', score: 78, value: 78 },
  { month: '10月', score: 82, value: 82 },
  { month: '11月', score: 79, value: 79 },
  { month: '12月', score: 85, value: 85 },
  { month: '1月', score: 83, value: 83 },
  { month: '2月', score: 87, value: 87 }
])

// 监听科目变化
watch(selectedSubject, (newSubject) => {
  console.log('科目已切换为:', newSubject)
})

// 生命周期
onMounted(async () => {
  try {
    await Promise.all([
      studentStore.fetchStudents(),
      appStore.fetchClasses(),
      appStore.fetchCourses()
    ])
  } catch (error) {
    console.error('加载数据失败:', error)
  }
})
</script>

<style scoped>
.statistics-page {
  padding: 0;
}

.page-title {
  margin-bottom: 20px;
  color: #303133;
  font-weight: 500;
}

.overview-stats {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.stat-icon {
  font-size: 32px;
  margin-right: 15px;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.primary-card .stat-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.success-card .stat-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.warning-card .stat-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.danger-card .stat-icon {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 2px;
}

.stat-change {
  font-size: 10px;
  color: #67C23A;
}

.charts-section {
  margin-bottom: 20px;
}

.chart-card {
  border-radius: 8px;
  min-height: 300px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
}

.score-distribution {
  padding: 10px 0;
}

.score-range {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.range-label {
  width: 80px;
  font-size: 12px;
  color: #606266;
}

.range-bar {
  flex: 1;
  height: 20px;
  background: #f5f7fa;
  border-radius: 10px;
  margin: 0 10px;
  overflow: hidden;
}

.range-fill {
  height: 100%;
  border-radius: 10px;
  transition: width 0.5s ease;
}

.range-value {
  width: 100px;
  font-size: 12px;
  color: #606266;
  text-align: right;
}

.gender-distribution {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 250px;
}

.gender-chart-container {
  display: flex;
  align-items: center;
  gap: 30px;
}

.pie-chart {
  position: relative;
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background: conic-gradient(#409EFF 0deg 180deg, #F56C6C 180deg 360deg);
}

.pie-center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 60px;
  height: 60px;
  background: white;
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.total-count {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.total-label {
  font-size: 10px;
  color: #909399;
}

.legend {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.legend-item {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #606266;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 2px;
  margin-right: 8px;
}

.male-color {
  background: #409EFF;
}

.female-color {
  background: #F56C6C;
}

.class-comparison {
  margin-bottom: 20px;
}

.class-scores {
  padding: 20px 0;
}

.class-score-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.class-name {
  width: 200px;
  font-size: 14px;
  color: #303133;
}

.score-bar {
  flex: 1;
  height: 20px;
  background: #f5f7fa;
  border-radius: 10px;
  margin: 0 15px;
  overflow: hidden;
}

.score-fill {
  height: 100%;
  background: linear-gradient(90deg, #409EFF 0%, #67C23A 100%);
  border-radius: 10px;
  transition: width 0.5s ease;
}

.score-value {
  width: 60px;
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  text-align: right;
}

.trend-section {
  margin-bottom: 20px;
}

.trend-chart {
  position: relative;
  height: 200px;
  padding: 20px;
}

.trend-line {
  position: relative;
  height: 150px;
  border-bottom: 1px solid #e4e7ed;
  border-left: 1px solid #e4e7ed;
}

.trend-point {
  position: absolute;
  transform: translateX(-50%);
}

.point-dot {
  width: 8px;
  height: 8px;
  background: #409EFF;
  border-radius: 50%;
  border: 2px solid white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.point-label {
  position: absolute;
  top: -25px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 12px;
  color: #303133;
  background: white;
  padding: 2px 6px;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.trend-labels {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.label-item {
  font-size: 12px;
  color: #909399;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .overview-stats .el-col {
    margin-bottom: 10px;
  }
  
  .stat-number {
    font-size: 20px;
  }
  
  .stat-icon {
    font-size: 24px;
    width: 40px;
    height: 40px;
  }
  
  .gender-chart-container {
    flex-direction: column;
    gap: 20px;
  }
  
  .class-score-item {
    flex-direction: column;
    align-items: stretch;
    gap: 5px;
  }
  
  .class-name {
    width: auto;
  }
  
  .score-bar {
    margin: 0;
  }
  
  .score-value {
    width: auto;
    text-align: left;
  }
}
</style> 